import type { App } from 'vue'
import { useUserStore } from '@/stores'
//辅助函数
//因定义的时候，按照权限顺序排列，所以这里直接用index判断
const FUNCTION_MAP = new Map<string, Function>([
  [
    'clan',
    (val: STORE.UserRoleInClan) => {
      const userStore = useUserStore()
      const userRoleIndex = userStore.USER_CLAN_ROLE_LIST.findIndex(
        (item) => item === userStore.userCurrentClan.roleName,
      )
      const deedRoleIndex = userStore.USER_CLAN_ROLE_LIST.findIndex((item) => item === val)
      return userRoleIndex >= deedRoleIndex
    },
  ],
  [
    'council',
    (val: STORE.UserRoleInCouncil) => {
      const userStore = useUserStore()
      if (!userStore.userCurrentCouncil) return false
      const userRoleIndex = userStore.USER_COUNCIL_ROLE_LIST.findIndex(
        (item) => item === userStore.userCurrentCouncil?.roleName,
      )
      const deedRoleIndex = userStore.USER_COUNCIL_ROLE_LIST.findIndex((item) => item === val)
      return userRoleIndex >= deedRoleIndex
    },
  ],
])
/**
 * 权限指令
 * @param value：传入此dom可以显示的最低权限，如："家族管理员",那么"家族管理员和家族会长都可见。
 * @param modifiers：修饰符，家族内部层面填clan，理事会层面填council
 */
export default function (app: App) {
  app.directive('permission', {
    mounted(el, binding) {
      const { modifiers, value } = binding
      if (!modifiers.council && !modifiers.clan)
        throw new Error('permission指令必须指定clan或council修饰符')
      const key = modifiers.council ? 'council' : 'clan'
      if (!FUNCTION_MAP.get(key)!(value)) {
        el.remove()
      }
    },
  })
}
